<?php

namespace Package\RedisHelper\Connection;

use Package\RedisHelper\config\ConfigLoader;
use Package\RedisHelper\Exceptions\RedisConnectionException;

class ConnectionManager
{
    private static $connections = [];
    
    /**
     * 获取Redis连接实例
     *
     * @param mixed $config 配置源 (数组、文件路径、RedisConfig对象)
     * @param string $name 连接名称 (用于复用连接)
     */
    public static function getConnection($config, string $name = 'default'): RedisConnection
    {
        if (!isset(self::$connections[$name])) {
            $redisConfig = ConfigLoader::load($config);
            
            try {
                $redisConfig->validate();
            } catch (\InvalidArgumentException $e) {
                throw new RedisConnectionException("Invalid Redis configuration: " . $e->getMessage());
            }
            
            self::$connections[$name] = new RedisConnection($redisConfig);
        }
        
        return self::$connections[$name];
    }
    
    /**
     * 断开所有连接
     */
    public static function disconnectAll(): void
    {
        foreach (self::$connections as $connection) {
            $connection->disconnect();
        }
        self::$connections = [];
    }
    
    /**
     * 断开指定连接
     */
    public static function disconnect(string $name): void
    {
        if (isset(self::$connections[$name])) {
            self::$connections[$name]->disconnect();
            unset(self::$connections[$name]);
        }
    }
}